/*
 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <filesystem>
#include "preference_manager.h"
#include "edm_log.h"
#include "config_policy_utils.h"

namespace OHOS {
namespace EDM {
const int32_t MAX_CONFIG_PATH_LEN = 256;
const int32_t ERR_OK = 0;
const int32_t ERR_NG = -1;
const std::string PATH {"etc/multimodalinput/plugin_info.xml"};
int32_t PreferenceManager::InitPreferences()
{
    int32_t ret = GetConfigFileAbsolutePath();
    if (ret != ERR_OK) {
        EDMLOGE("Get input plugin setting path failed.");
        return ERR_NG;
    }
    if (!FileExists()) {
        EDMLOGE("input plugin file is not exists.");
        return ERR_NG;
    }
    ret = GetPreferencesSettings();
    if (ret != ERR_OK) {
        EDMLOGE("Get input plugin preferences setting failed.");
        return ERR_NG;
    }
    return ERR_OK;
}

int32_t PreferenceManager::GetPreferencesSettings()
{
    int32_t errCode = ERR_NG;
    std::shared_ptr<NativePreferences::Preferences> pluginPref = NativePreferences::PreferencesHelper::
        GetPreferences(configFileAbsolutePath_, errCode);
    supportedKeyCodes_ = pluginPref->GetString(supportedKeyCodesKey_, "");
    NativePreferences::PreferencesHelper::RemovePreferencesFromCache(configFileAbsolutePath_);
    return ERR_OK;
}

std::string PreferenceManager::GetSupportedKeyCodes() const
{
    return supportedKeyCodes_;
}

int32_t PreferenceManager::GetConfigFileAbsolutePath()
{
    char buffer[MAX_CONFIG_PATH_LEN] = {};
    if (GetOneCfgFile(PATH.c_str(), buffer, sizeof(buffer)) != nullptr) {
        configFileAbsolutePath_ = buffer;
        EDMLOGE("edmCustomize configFileAbsolutePath_ = %{public}s", configFileAbsolutePath_.c_str());
        return ERR_OK;
    }
    return ERR_NG;
}

bool PreferenceManager::FileExists()
{
    return std::filesystem::exists(configFileAbsolutePath_);
}
} // namespace EDM
} // namespace OHOS

